import {ref, watchEffect} from "vue";
//监听器watchEffect 相比于watch 更加轻量级,不需要显示声明依赖
//自己跟据函数体内的依赖去判断
//namem key
//value 初始值
export const useStorage = (name: string, value = [{}]) => {
    const storedValue = localStorage.getItem(name);
    let parsedValue;
    if (storedValue !== null) {
        try {
            parsedValue = JSON.parse(storedValue)
        } catch (error) {
            parsedValue = value
        }
    } else {
        parsedValue = value
    }
    let data = ref(parsedValue)
    // let data=ref(JSON.parse(localStorage.getItem(name))||{})
    watchEffect(() => {
        localStorage.setItem(name, JSON.stringify(data.value))
    })
    return data
}


